<template>
  <div>
    <div class="operation-bar">
      <el-button type="warning" @click="addProduct">新增商品</el-button>
      <el-button
        type="danger"
        @click="batchDelete"
        :disabled="selectedIds.length === 0"
      >
        批量删除
      </el-button>
      <div class="search-bar">
        <el-input
          v-model="searchName"
          placeholder="商品名称"
          style="width: 200px"
        ></el-input>
        <el-input
          v-model="searchId"
          placeholder="商品编号"
          style="width: 200px; margin-left: 10px"
        ></el-input>
        <el-select
          v-model="searchCategory"
          placeholder="商品分类"
          style="width: 200px; margin-left: 10px"
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          ></el-option>
        </el-select>
        <el-select
          v-model="searchStatus"
          placeholder="是否上架"
          style="width: 200px; margin-left: 10px"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="上架" :value="1"></el-option>
          <el-option label="下架" :value="0"></el-option>
        </el-select>
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="fetchProducts"
          >搜索</el-button
        >
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="currentProduct.id ? '编辑商品' : '新增商品'"
      width="50%"
    >
      <el-form :model="currentProduct" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="currentProduct.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input-number
            v-model="currentProduct.price"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存">
          <el-input-number
            v-model="currentProduct.stock"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="currentProduct.category" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            action="/api/upload"
            :on-success="handleUploadSuccess"
            :show-file-list="false"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传商品图片</div>
            </template>
          </el-upload>
          <el-image
            v-if="currentProduct.image"
            :src="currentProduct.image"
            style="width: 100px; height: 100px"
          ></el-image>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input
            type="textarea"
            v-model="currentProduct.description"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>

    <el-table
      :data="products"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="商品图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            style="width: 50px; height: 50px"
            :preview-src-list="[row.image]"
            hide-on-click-modal
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="categoryName" label="分类"></el-table-column>
      <el-table-column prop="price" label="价格" width="120"></el-table-column>
      <el-table-column prop="sales" label="销量" width="100"></el-table-column>
      <el-table-column prop="stock" label="库存" width="100"></el-table-column>
      <el-table-column
        prop="returns"
        label="退货数量"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="returnAmount"
        label="退货金额"
        width="120"
      ></el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "上架" : "下架" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="admin"
        label="管理员"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180"
      ></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="editProduct(row)">编辑</el-button>
          <el-button
            size="small"
            :type="row.status === 1 ? 'warning' : 'success'"
            @click="toggleStatus(row)"
          >
            {{ row.status === 1 ? "下架" : "上架" }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteProduct(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, total"
      @current-change="fetchProducts"
      style="margin-top: 20px"
    ></el-pagination>
  </div>
</template>

<script setup>
import { ref, onMounted, shallowRef, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import productsData from "./products.json";

const products = ref([]);
const categories = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const selectedIds = ref([]);
const searchName = ref("");
const searchId = ref("");
const searchCategory = ref("");
const searchStatus = ref("");
const tableRef = shallowRef(null);

const currentProduct = ref({
  id: null,
  name: "",
  price: 0,
  stock: 0,
  category: "",
  image: "",
  description: "",
  status: 1,
  sales: 0,
  returns: 0,
  returnAmount: 0,
  admin: "",
  updateTime: "",
});

const fetchProducts = async () => {
  // Filter products based on search criteria
  let filtered = [...productsData.products];

  if (searchName.value) {
    filtered = filtered.filter((p) => p.name.includes(searchName.value));
  }

  if (searchId.value) {
    filtered = filtered.filter((p) => p.id.toString() === searchId.value);
  }

  if (searchCategory.value) {
    filtered = filtered.filter(
      (p) => p.category.toString() === searchCategory.value
    );
  }

  if (searchStatus.value !== "") {
    filtered = filtered.filter(
      (p) => p.status.toString() === searchStatus.value
    );
  }

  // Pagination logic
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;

  products.value = filtered.slice(start, end);
  total.value = filtered.length;
  categories.value = productsData.categories;

  // 重置选中状态
  nextTick(() => {
    if (tableRef.value) {
      tableRef.value.clearSelection();
      selectedIds.value = [];
    }
  });
};

const fetchCategories = async () => {
  categories.value = productsData.categories;
};

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map((item) => item.id);
};

const batchDelete = () => {
  ElMessageBox.confirm("确定删除选中的商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 从原始数据中删除
      productsData.products = productsData.products.filter(
        (p) => !selectedIds.value.includes(p.id)
      );
      // 更新当前页数据
      fetchProducts();
      selectedIds.value = [];
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

const deleteProduct = (product) => {
  ElMessageBox.confirm("确定删除此商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 从原始数据中删除
      productsData.products = productsData.products.filter(
        (p) => p.id !== product.id
      );
      // 更新当前页数据
      fetchProducts();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
};

const addProduct = () => {
  currentProduct.value = {
    id: null,
    name: "",
    price: 0,
    stock: 0,
    category: "",
    image: "",
    description: "",
    status: 1,
    sales: 0,
    returns: 0,
    returnAmount: 0,
    admin: "当前管理员",
    updateTime: new Date().toLocaleString(),
  };
  dialogVisible.value = true;
};

const editProduct = (product) => {
  currentProduct.value = { ...product };
  dialogVisible.value = true;
};

const saveProduct = () => {
  if (!currentProduct.value.name) {
    ElMessage.error("请输入商品名称");
    return;
  }

  if (currentProduct.value.id) {
    // Update product
    const index = productsData.products.findIndex(
      (p) => p.id === currentProduct.value.id
    );
    if (index !== -1) {
      productsData.products[index] = { ...currentProduct.value };
    }
    ElMessage.success("商品更新成功");
  } else {
    // Add new product
    currentProduct.value.id =
      productsData.products.length > 0
        ? Math.max(...productsData.products.map((p) => p.id)) + 1
        : 1;
    productsData.products.unshift({ ...currentProduct.value });
    total.value += 1;
    ElMessage.success("商品添加成功");
  }

  // 更新当前页数据
  fetchProducts();
  dialogVisible.value = false;
};

const toggleStatus = (product) => {
  product.status = product.status === 1 ? 0 : 1;
  product.updateTime = new Date().toLocaleString();
  ElMessage.success(`商品已${product.status === 1 ? "上架" : "下架"}`);
};

const handleUploadSuccess = (response) => {
  currentProduct.value.image = response.url;
  ElMessage.success("图片上传成功");
};

onMounted(() => {
  fetchProducts();
  fetchCategories();
});
</script>

<style scoped>
.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
.search-bar {
  margin-left: auto;
  display: flex;
}
</style>
